/*
 * change different short dates to appropriate pairs
 * empty -> today
 * +5 -> today+5
 * 16 -> 16th, this month
 * 	12-16 -> this year-12-16
 * 	9-2-16 -> 2009-02-16
 * 	12-2-26 -> 2012-02-26
 * 	912-2-11 -> 1912-02-11
*/

(function($){
	$.fn.easydate = function(options){
		
		var settings = $.extend({
			delimeter	: '-',
			format		: 'Y-m-d'
			}, options );
		
		var $input = this;
		if(!$input.is(":input")){
			console.log('easydate should be called for an input element');
			return;
		}
		
		$input.bind('blur.easydate', function(){
			var dateString = $input.val(),
				currentDate = new Date();
			if(isNaN(parseInt(dateString))) {
				console.log('The given value is not a number, setting current date');
			}
			else{
				//we got something like a number
				if (dateString.match(/^\d+$/)) {		//if we got just a number: actual year, month and that day if exists or next month if day is bigger than 31
					currentDate.setDate(parseInt(dateString));
				}
				else if (dateString.search(/\+/) == 0) {		//if date starts with + sign than it means today+x day
					currentDate.setDate(currentDate.getDate() + parseInt(dateString));
				}
				else{
					var d = dateString.split(settings.delimeter);		//if the dateString conatins delimeter we should split it
					if (d.length == 2) {		//only one delimeter: month and day
						currentDate.setMonth(d[0] - 1);
						currentDate.setDate(d[1]);
					}
					else if (d.length == 3) {		//2 delimeters: year, month and day
						if (d[0]['length'] == 1) {
							currentDate.setFullYear('200' + d[0]);
						}
						else if (d[0]['length'] == 2) {
							currentDate.setFullYear('20' + d[0]);
						}
						else if (d[0]['length'] == 3) {
							currentDate.setFullYear('1	' + d[0]);
						}
						else if (d[0]['length'] == 4) {
							currentDate.setFullYear(d[0]);
						}
						currentDate.setMonth(d[1] - 1);
						currentDate.setDate(d[2]);
					}
					else{
						console.log('The given value is unhandled, setting cutrrent date');
					}
				}
			}
			$input.val(changeDelimeter(formatDate(currentDate)));
			
		});
		
		function changeDelimeter(dateString){
			return dateString.replace(/-/g, settings.delimeter);
		}
		
		function formatDate(date){
			var month = (date.getMonth() + 1).toString();
			month = (month.length == 1) ? '0' + month : month;
			var day = date.getDate().toString();
			day = (day.length == 1) ? '0' + day : day;
			return(date.getFullYear() + '-' + month + '-' + day);
		}
		
		return this;	//required for chaining
	}
}(jQuery));